using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using GSync.GoogleSystem;

namespace GSync
{
    public partial class Main : Form
    {
#region property
        /// <summary>
        /// Google service's Manager
        /// </summary>
        private GManager gcal;
        private GContact gCont;

        /// <summary>
        /// Configuration wrapper
        /// </summary>
        private Config config = null;
        ///
        private  ArrayList ComboTypes = new ArrayList();
#endregion


        /// <summary>
        /// Costructor
        /// </summary>
        public Main()
        {
            ComboTypes.Add(new ComboItem(Properties.Resources.MSG_USE_ORIGINE,GManager.OUTLOOK_ITEM));
            ComboTypes.Add(new ComboItem(Properties.Resources.MSG_USE_DESTINATION, GManager.GOOGLE_ITEM));
            ComboTypes.Add(new ComboItem(Properties.Resources.MSG_USE_DUPLICATE, GManager.DUPLICATE_ITEM));
            ComboTypes.Add(new ComboItem(Properties.Resources.MSG_USE_ASK_ME, GManager.ASK_ACTION));


            InitializeComponent();
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            String vesion = assembly.GetName().Version.ToString();
            versionLabel.Text += " "+vesion;
            clearStatus();
            InitializeConfig();
            conflicResolverMethod.DataSource = ComboTypes;
            conflicResolverMethod.DisplayMember = "Name";
            conflicResolverMethod.ValueMember = "Value";


        }
        #region status method
        /// <summary>
        /// Clear the application status, set to initial status of gui and config
        /// </summary>
        private void clearStatus()
        {
            calToSynch.Items.Clear();
            eventBox.Items.Clear();
            openCalButton.Enabled = false;
            defaulCalButton.Enabled = false;
            eventView.Text = "";
            eventView.Visible = false;
            viewItem.Enabled = false;
            importSingle.Enabled = false;
            if (config != null)
            {
                defaultCalendar.Text = Properties.Resources.LABEL_DEFAULT_CAL + (config.DefaultGCalName != null ? config.DefaultGCalName : Properties.Resources.LABEL_NOT_SET);
                maxItems.Text = config.MaxResults.ToString();
            }

            
            this.startDatePicker.Value = DateTime.Now;
            this.endDatePicker.Value = DateTime.Now.AddYears(1);
        }
        /// <summary>
        /// Initialize Config, read the configuration from registry and set 
        /// the default value
        /// </summary>
        private void InitializeConfig()
        {
            //Leggi le credenziali
            config = Config.load();
            
            //inizializza i campi text
            if (config.Credential!=null && config.Credential.Setted)
            {
                userName.Text = config.Credential.UserName;
                password.Text = config.Credential.Password;
                saveLogin.Checked = true;
            }
            deleteBeforeCheck.Checked = config.DefaultDeleteBeforeImport;
            maxItems.Text = config.MaxResults.ToString();
            defaultCalendar.Text = Properties.Resources.LABEL_DEFAULT_CAL + (config.DefaultGCalName != null ? config.DefaultGCalName : Properties.Resources.LABEL_NOT_SET);
            if (config.getDefaultCalItem() != null && (calToSynch.Items == null || calToSynch.Items.Count == 0))
            {
                calToSynch.Items.Add(config.getDefaultCalItem());               
                openCalButton.Enabled = true;
            }
            queryBox.Visible = config.ShowFilter;
            queryBox.Text = config.defaultQuery();
        }

        /// <summary>
        /// Initialize th google service manager
        /// </summary>
        private Boolean initializeGManager()
        {
            if (config == null || !config.Credential.Setted)
            {
                MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + Properties.Resources.MSG_ACCESS_DATA);
                return false;
            }
            waitCursor();
            gcal = GManager.getInstance(config);
            gCont = GContact.getInstance(config);
            defaultCursor();
            return true;
        }

        /// <summary>
        /// Imposta sulla configurazione il valore del calendario di default
        /// poi viene salvato su registro
        /// </summary>
        /// <param name="defaultGCalName"></param>
        private void setDefaultCal(GSItem defaultGCalName)
        {
            config.DefaultGCalName = defaultGCalName.Title.ToString();
            config.DefaultGCalFeedURI = defaultGCalName.Id.ToString();//gcal.getFeedURI(defaultGCalName);
            config.setDefaultCal();
        }


        /// <summary>
        /// Open wait cursor
        /// </summary>
        /// <returns></returns>
        private Cursor waitCursor()
        {
            Cursor prevCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            return prevCursor;
        }
        /// <summary>
        /// Set default cursor
        /// </summary>
        /// <returns></returns>
        private Cursor defaultCursor()
        {
            Cursor prevCursor = Cursor.Current;
            Cursor.Current = Cursors.Default;
            return prevCursor;
        }

        private void calculateContact()
        {
            if (!initializeGManager())
            {
                return;
            }
            int outlookContacts = gcal.getOutlookSession().Contacts.Items.Count;
            int outlookImportedContact = gcal.getOutlookSession().Contacts.Items.Restrict("[Categories]=\"GoogleImported\"").Count; //AND [Start] = "+AppAppts.Start));
            int googleContacts = gCont.Contacts.Count;
            googleC.Text = Properties.Resources.LABEL_THERE_ARE + " " + googleContacts + " " + Properties.Resources.LABEL_CONTACTS;
            outlookC.Text = Properties.Resources.LABEL_THERE_ARE + " " + outlookContacts + " " + Properties.Resources.LABEL_CONTACTS + ". " + Properties.Resources.LABEL_IMPORTED + " " + outlookImportedContact;

        }

#endregion
        #region event
        /// <summary>
        /// Geenra la lista di eventi di un calendario e la mostra nell'eventBox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void synch_Click(object sender, EventArgs e)
        {
            if (gcal == null)
            {
                if (config == null || !config.Credential.Setted)
                {
                    MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + Properties.Resources.MSG_ACCESS_DATA);
                    return;
                }
                gcal = GManager.getInstance(config);
            }
           // gcal.setExtraParam(queryBox.Text.ToString());
            eventBox.Items.Clear();
            if (calToSynch.SelectedItem != null)
            {
                waitCursor();
                try
                {
                    String value = ((GSItem)calToSynch.SelectedItem).Title.ToString();
                    ArrayList events = gcal.GetAllEvents(value);
                    statusBar.Text = Properties.Resources.LABEL_FOUND+" " + events.Count + " "+Properties.Resources.LABEL_TAB_VIEW;
                    eventBox.BeginUpdate();
                    foreach (GSItem item in events)
                    {
                        eventBox.Items.Add(item);
                    }
                    eventBox.EndUpdate();
                    viewItem.Enabled = true;
                    importSingle.Enabled = true;
                    int gotoPanel=tabControll.TabPages.IndexOf(ViewPanel);
                    tabControll.SelectedIndex = gotoPanel;
                    ViewPanel.Focus();
                }
                catch (Exception ge)
                {
                    MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + ge.Message);
                }
                finally
                {
                    defaultCursor();
                }
            }
        }


        /// <summary>
        /// Inizializza la lista dei calendari
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void initializeCal_Click(object sender, EventArgs e)
        {
            if (initializeGManager())
            {
                waitCursor();

                try
                {
                    openCalButton.Enabled = false;
                    defaulCalButton.Enabled = false;
                    ICollection cal = gcal.RetriveUserCalendars();
                    GSItem lastCal = null;
                    calToSynch.BeginUpdate();
                    calToSynch.Items.Clear();
                    //            calendari.Add("Tutti", "http://www.google.com/calendar/feeds/default");
                    foreach (GSItem item in cal)
                    {
                        calToSynch.Items.Add(item);
                        lastCal = item;
                    }
                    calToSynch.EndUpdate();
                    if (cal.Count == 1)
                    {
                        setDefaultCal(lastCal);
                    }
                }
                catch (Exception ge)
                {
                    MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + ge.Message);

                    return;
                }
                finally
                {
                    defaultCursor();
                }
                openCalButton.Enabled = true;
                defaulCalButton.Enabled = true;
            }
        }

       

        /// <summary>
        /// Mostra i dati di un evento, selezionato dalla lista
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void viewItem_Click(object sender, EventArgs e)
        {
            try
            {
                waitCursor();
                GSItem selItem = (GSItem)eventBox.SelectedItem;
                String value = selItem.Id.ToString();

                eventView.Text = gcal.getEventEntryToString(value);
                eventView.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + ex.Message);
            }
            finally
            {
                defaultCursor();
            }
        }

        /// <summary>
        /// Importa il singolo evento
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void importSingle_Click(object sender, EventArgs e)
        {
            if (eventBox.SelectedItem == null)
            {
                MessageBox.Show(Properties.Resources.MSG_EVENT_NOT_SELECTED);
            }
            else
            {
                waitCursor();
                try
                {
                    GSItem selItem = (GSItem)eventBox.SelectedItem;
                    String value = selItem.Id.ToString();
                    gcal.importGCal(value);
                    
                    //   gcal.removeAppoint();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                    MessageBox.Show(Properties.Resources.MSG_ALERT+":"+ex.Message);
                }
                finally
                {
                    defaultCursor();
                }
            }
        }

        /// <summary>
        /// Nasconde i dati di un evento
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void close_Click(object sender, EventArgs e)
        {
            eventView.Text = "";
            eventView.Visible = false;
        }


        /// <summary>
        /// Crea un evento nel pocket calendar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void importItem_Click(object sender, EventArgs e)
        {
            tabControll.SelectedIndex = 0;
            calPage.Focus();
            String value = config.DefaultGCalName;
            Boolean useDefault = true;
            if (calToSynch.SelectedItem != null)
            {
                value=calToSynch.SelectedItem.ToString();
                useDefault = false;
            }
            else if (config.DefaultGCalFeedURI==null)
            {
                MessageBox.Show(Properties.Resources.MSG_CALENDAR_NOT_SELECTED);
                return;
            }
            int imported = 0;
            int editati = 0;
            try
            {
                statusBar.Text = Properties.Resources.LABEL_SET_CAL+" " + value;
                statusBar.Update();
                importBar.Visible = true;
                importBar.Value = 0;
                ArrayList events=null;
                if (!initializeGManager())
                {
                    return;
                }

                waitCursor();
                if (useDefault)
                {
                    String feedName = config.DefaultGCalFeedURI;
                    events = gcal.GetAllEventsByFeed(feedName);
                }
                else
                {
                    events = gcal.GetAllEvents(value);
                }
                defaultCursor();
                importBar.Maximum = events.Count;
                statusBar.Text = Properties.Resources.LABEL_FOUND+" " + events.Count+" "+Properties.Resources.LABEL_TAB_VIEW;
                statusBar.Update();
                //cancella prima
                if (config.DefaultDeleteBeforeImport)
                {
                    importBar.Maximum += 1;
                    
                    try
                    {
                        waitCursor();
                        int rimossi=gcal.removeAppoint();
                        defaultCursor();
                        statusBar.Text = Properties.Resources.MSG_DELETED+" "+rimossi+" "+Properties.Resources.LABEL_TAB_VIEW;
                        statusBar.Update();
                        
                    }
                    catch (Exception e1)
                    {
                        Debug.WriteLine(e1.Message);
                        Debug.WriteLine(e1.StackTrace);
                    }
                    importBar.Value += 1;                    
                }
                //importa

                foreach (GSItem eEvent in events)
                {
                    try
                    {
                        int action=gcal.importGCal(eEvent.Id);
                        if (action == GManager.INSERT_ITEM)
                        {
                            imported++;
                        }
                        else if (action == GManager.EDITED_ITEM)
                        {
                            editati++;
                        }
                        statusBar.Text = (action == GManager.INSERT_ITEM ? Properties.Resources.MSG_IMPORTED : Properties.Resources.MSG_EDITED)+" " + gcal.getEventNameByEventId(eEvent.Id);
                        statusBar.Update();
                    }
                    catch (Exception e1)
                    {
                        Debug.WriteLine(e1.Message);
                        Debug.WriteLine(e1.StackTrace);
                    }
                    importBar.Value += 1;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }
            finally
            {

                MessageBox.Show(Properties.Resources.MSG_IMPORTED + ": " + imported + " " + Properties.Resources.MSG_EVENT_OF_CAL + ": " + value + "\n " + Properties.Resources.MSG_EDITED + ": " + editati + " " + Properties.Resources.MSG_EVENT_OF_CAL + ": " + value);
                importBar.Value = 0;
                importBar.Visible = false;
                defaultCursor();
            }

        }

        

        /// <summary>
        /// OK config event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loginOk_Click(object sender, EventArgs e)
        {
            
            String user = userName.Text.Trim();
            String paswd = password.Text.Trim();

            try
            {
                config.MaxResults = int.Parse(maxItems.Text.ToString());
            }
            catch (Exception ex)
            {
                config.MaxResults = 25;
                maxItems.Text = "25";
                Debug.WriteLine(ex.StackTrace);
            }

            if (config.Credential != null && config.Credential.UserName != user)
            {
                clearStatus();
            }
            else if (config.Credential == null)
            {
                config.Credential = new Credential();
            }
            Boolean change = false;
            if (config.Credential.UserName != user)
            {
                config.Credential.UserName = user;
                change = true;
            }
            if (config.Credential.Password != paswd)
            {
                config.Credential.Password = paswd;
                change = true;
            }
            Boolean changeOption = false;
            if (config.SaveCredential != saveLogin.Checked ||
                config.DefaultDeleteBeforeImport != deleteBeforeCheck.Checked)
            {
                config.SaveCredential = saveLogin.Checked;
                config.DefaultDeleteBeforeImport = deleteBeforeCheck.Checked;
                changeOption = true;
            }

            config.save();
            Credential temp = config.Credential;
            config = Config.load(temp);
            
            if (gcal != null && change)
            {
                gcal.Config = config;
            }
            else if (gcal != null && changeOption)
            {
                gcal.Config.SaveCredential = saveLogin.Checked;
                gcal.Config.DefaultDeleteBeforeImport = deleteBeforeCheck.Checked;
            }
            
            defaultCalendar.Text = Properties.Resources.LABEL_DEFAULT_CAL + (config.DefaultGCalName != null ? config.DefaultGCalName : Properties.Resources.LABEL_NOT_SET);
            tabControll.SelectedIndex=0;
            calPage.Focus();
           
        }


        /// <summary>
        /// Cancel config event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loginCancel_Click(object sender, EventArgs e)
        {
            InitializeConfig();
            //clearStatus();
            tabControll.SelectedIndex = 0;
            calPage.Focus();
        }



        /// <summary>
        /// set the default calendsar
        /// Preleva il valore del calendario di deault dalla combo dei calendari
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void defaulCal_Click(object sender, EventArgs e)
        {
            waitCursor();
            GSItem value = (GSItem)calToSynch.SelectedItem;
            setDefaultCal(value);
            defaultCursor();
            defaultCalendar.Text = Properties.Resources.LABEL_DEFAULT_CAL + (config.DefaultGCalName != null ? config.DefaultGCalName : Properties.Resources.LABEL_NOT_SET);
        }

      

        /// <summary>
        /// RRemove all imported Google's cal events
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void removeImportedGCal(object sender, EventArgs e)
        {
            string message = Properties.Resources.MSG_DELETE_ALL;
            string caption = Properties.Resources.MSG_ALERT;
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;

            // Displays the MessageBox.

            result = MessageBox.Show(message, caption, buttons,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);

            if (result == DialogResult.Yes)
            {

                if (!initializeGManager())
                {
                    return;
                }
                waitCursor();
                int rimossi = gcal.removeAppoint();
                defaultCursor();
                MessageBox.Show(Properties.Resources.MSG_DELETED + ": " + rimossi + " " + Properties.Resources.MSG_EVENT_OF_CAL);
            }
        }
        
        /// <summary>
        /// Validator of max item config field
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void maxItems_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                int.Parse(((TextBox)sender).Text.ToString());
                e.Cancel = false;
            }
            catch(Exception ex)
            {
                MessageBox.Show(Properties.Resources.MSG_ALERT+"\r\n"+ex.Message);
                e.Cancel=true;
            }
        }

        /// <summary>
        /// Change tab event of tabPage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabPage_openTab(object sender, EventArgs e)
        {
            //Apre il tab About            
            if (tabControll.SelectedIndex == tabControll.TabPages.IndexOf(aboutPage) && !timer1.Enabled)
            {
                logoBox.Visible = true;
                timer1.Enabled = true;
            }
            //Apre il tab Contatti
            if (tabControll.SelectedIndex == tabControll.TabPages.IndexOf(contacts))
            {
                calculateContact();
                //googleImported.Text = Properties.Resources.LABEL_THERE_ARE + " " + outlookImportedContact + " " + Properties.Resources.LABEL_CONTACTS;
            }
            if (tabControll.SelectedIndex == tabControll.TabPages.IndexOf(infoPane))
            {
                if (!initializeGManager())
                {
                    return;
                }
                TimeZone localZone = TimeZone.CurrentTimeZone;
                DateTime currentUTC =
                        localZone.ToUniversalTime(DateTime.Now);


                info1.Text = localZone.StandardName + " (" + localZone.GetUtcOffset(currentUTC) + ") ";
                DateTime outlookDate = gcal.getVoidAppDate();

                info2.Text = outlookDate.Kind + " " + " (" + localZone.GetUtcOffset(outlookDate) + ")(" + localZone.GetUtcOffset(localZone.ToLocalTime(outlookDate)) + ")";
            }
        }

      

        /// <summary>
        /// Start timer for aniomation of aboyt page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            logoBox.Visible = false;
            timer1.Enabled = false;
        }
        /// <summary>
        /// open link in IE
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenLOcationFromTxtBox(object sender, EventArgs e)
        {
            Process.Start("IExplore.exe", ((LinkLabel)sender).Text.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void queryBox_TextChanged(object sender, EventArgs e)
        {
            config.Query = ((TextBox)sender).Text.ToString();
        }

        private void saveLogin_CheckStateChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Applica i filtri
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void applyFilter_Click(object sender, EventArgs e)
        {
            String startDateFilter = startDatePicker.Text;
            String endDateFilter = endDatePicker.Text;
            int index = orderCombo.SelectedIndex;
            if (index == -1)
            {
                index = 0;
            }
            String[] orders ={ "starttime", "lastmodified" };
           
            if (titleFilterText.Text != null && titleFilterText.Text.Trim().Length > 0)
            {
               config.TextFilter= titleFilterText.Text;
            }
            queryBox.Text = "orderby="+orders[index ]+"&start-min=" + startDateFilter + "&start-max=" + endDateFilter+"&&max-results="+config.MaxResults;
        }


        private void importContactsFromGoogle(object sender, EventArgs e)
        {
            String bName = ((Button)sender).Name.ToString();
            int way = (bName.IndexOf("G2O") > -1 ? GManager.WAY_OUTLOOK :
                (bName.IndexOf("O2G") > -1 ? GManager.WAY_GOOGLE :
                GManager.WAY_BOTH));
            if (gCont == null)
            {
                if (config == null || !config.Credential.Setted)
                {
                    MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + Properties.Resources.MSG_ACCESS_DATA);
                    return;
                }
                gCont = GContact.getInstance(config);
            }
            //Carico i contatti di Google
            

        }

        private void importContactsFromGoogleOld(object sender, EventArgs e)
        {
            try
            {
                String bName=((Button)sender).Name.ToString();
                int way = (bName.IndexOf("G2O") > -1 ? GManager.WAY_OUTLOOK : 
                    (bName.IndexOf("O2G") > -1 ? GManager.WAY_GOOGLE : 
                    GManager.WAY_BOTH));
                if (gcal == null)
                {
                    if (config == null || !config.Credential.Setted)
                    {
                        MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + Properties.Resources.MSG_ACCESS_DATA);
                        return;
                    }
                    gcal = GManager.getInstance(config);
                }
                int googleContacts = gcal.Contacts.Count;
                
                if (googleContacts < 1)
                {
                    string message = Properties.Resources.LABEL_THERE_ARE + " " + googleContacts + " " + Properties.Resources.LABEL_CONTACTS + ".\n\r" + Properties.Resources.MSG_LOAD+"?";
                    string caption = Properties.Resources.MSG_ALERT;
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    DialogResult result;
                    result = MessageBox.Show(message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    //MessageBox.Show(Properties.Resources.LABEL_THERE_ARE + "  " + googleContacts + " " + Properties.Resources.LABEL_CONTACTS);
                    if (result == DialogResult.No)
                    {
                        return;
                    }
                    else
                    {
                        waitCursor();
                        gCont.retriveContacts();
                        googleContacts = gcal.Contacts.Count;
                        if (googleContacts < 1)
                        {
                            MessageBox.Show(Properties.Resources.LABEL_THERE_ARE + "  " + googleContacts + " " + Properties.Resources.LABEL_CONTACTS);
                            return;
                        }
                    }
                }
                importContact.Visible = true;
                importContact.Value = 0;
                importContact.Maximum = googleContacts;
                waitCursor();
                int importati = 0;
                int editati = 0;
                gcal.resetToImport();
                int selectOptionValue =(int)conflicResolverMethod.SelectedValue;
                foreach (GSItem contact in gcal.Contacts)
                {
                    Hashtable diff = new Hashtable();
                    int action = gCont.importContactGToO(contact, diff, selectOptionValue, way);
                    importContact.Value += 1;
                    switch(action)
                    {
                        case GManager.NOP_ITEM:
                            break;
                        case GManager.INSERT_ITEM:                    
                            importati++;
                            break;
                        case GManager.EDITED_ITEM:
                            editati++;
                            switch(selectOptionValue)
                            {
                                case 0: //Usa Outlook 
                                    //Aggiungo a google
                                    break;
                                case 1: //Usa Google
                                    //aggiungo in outlook
                                    break;
                                case 2: //Chiedimelo                            
                                defaultCursor();
                                ContactForm f = new ContactForm(diff);
                                f.ShowDialog();

                                Debug.WriteLine(diff["RESULT"]);
                                if (diff["RESULT"] != null)
                                {
                                    Object[] contacts = (Object[])diff[GManager.CONTACT_ITEM];
                                    int state = (int)diff["RESULT"];
                                    switch (state)
                                    {
                                        case GManager.GOOGLE_ITEM:


                                            gCont.editOutlookContact(contacts);
                                            break;
                                        case GManager.OUTLOOK_ITEM:
                                            //aggiungo a google
                                            gCont.addToEditedGoogle(contact.googleContact, contacts[GManager.OUTLOOK_ITEM]);
                                            break;
                                    }
                                }
                                waitCursor();
                                break;
                                case 3: // Copia
                                    //Copio in outlook e aggiungo pure in google
                                    break;
                            }
                            break;
                            
                    }
                }
                if (way != GManager.WAY_OUTLOOK)
                {
                    gCont.addContactToGoogle(selectOptionValue);
                }
                //googleImported.Text = "";
                googleImported.Text = importati + " " + Properties.Resources.MSG_IMPORTED + "/"+editati+" " + Properties.Resources.MSG_EDITED;
                calculateContact();
                MessageBox.Show(Properties.Resources.LABEL_CONTACTS + " " + Properties.Resources.LABEL_IMPORTED + " " + importati);
            }
            catch (Exception ge)
            {
                MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + ge.Message);
            }
            finally
            {
                defaultCursor();
            }
        }

        private void loadGoogleContacts(object sender, EventArgs e)
        {
            try
            {
                if (gCont == null)
                {
                    if (config == null || !config.Credential.Setted)
                    {
                        MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + Properties.Resources.MSG_ACCESS_DATA);
                        return;
                    }
                    gCont = GContact.getInstance(config);
                }               
                calculateContact();
                waitCursor();
                gCont.retriveContacts();
                int googleContacts = gcal.Contacts.Count;
                googleC.Text = Properties.Resources.LABEL_THERE_ARE + " " + googleContacts + " " + Properties.Resources.LABEL_CONTACTS;

            }
            catch (Exception ge)
            {
                MessageBox.Show(Properties.Resources.MSG_ALERT + "\r\n" + ge.Message);
            }
            finally
            {
                defaultCursor();
            }
        }


        private void deleteContact(object sender, EventArgs e)
        {
            string message = Properties.Resources.MSG_DELETE_ALL_CONTACT;
            string caption = Properties.Resources.MSG_ALERT;
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;

            // Displays the MessageBox.

            result = MessageBox.Show(message, caption, buttons,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);

            if (result == DialogResult.Yes)
            {
                try
                {
                    waitCursor();
                    gCont.deleteContact();
                    calculateContact();
                    googleImported.Text = "";
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                finally
                {
                    defaultCursor();
                }
            }
    
        }

      



#endregion

        private void logoBox_Click(object sender, EventArgs e)
        {
            try
            {
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://web.tiscali.it/w.spazio/gsync/gsync-0-3-2");//http://web.tiscali.it/w.spazio/gsync/GSyncCAB_031.CAB
                HttpWebResponse res = (HttpWebResponse)wr.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
                string versionInfo = sr.ReadToEnd();
                MessageBox.Show(versionInfo.Split(new char[] {':'})[0]);
            }
            catch (UriFormatException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }  
            
        }

        private void buttonConO2G_Click(object sender, EventArgs e)
        {

        }
        

    }



public class ComboItem
    {
        private string myShortName;
        private int myValue;

    public ComboItem(string strShortName, int value)
        {

            this.myShortName = strShortName;
            this.myValue = value;
        }

    public int Value
        {
            get
            {
                return myValue;
            }
        }

        public string Name
        {

            get
            {
                return myShortName;
            }
        }

    }

}